package com.neko.seed.util.redis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neko.seed.api.entity.BasePo;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.lang.reflect.Method;
import java.time.Duration;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        //对象的序列化
        RedisSerializationContext.SerializationPair valueSerializationPair
                = RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer());
        //全局redis缓存过期时间
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofDays(1))
//                .serializeKeysWith()
                .serializeValuesWith(valueSerializationPair);

        return new SpringRedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(factory), redisCacheConfiguration);
    }
//    private final RedisConnectionFactory redisConnectionFactory;
//    RedisConfig(RedisConnectionFactory redisConnectionFactory) {
//        this.redisConnectionFactory = redisConnectionFactory;
//    }
//    @Bean
//    @Override
//    public CacheManager cacheManager() {
//        // 初始化一个RedisCacheWriter
//        RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
//
//        // 设置默认过期时间：30 分钟
//        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
//                .entryTtl(Duration.ofMinutes(30))
//                // .disableCachingNullValues()
//                // 使用注解时的序列化、反序列化
//                .serializeKeysWith(SpringRedisCacheManager.STRING_PAIR)
//                .serializeValuesWith(SpringRedisCacheManager.FASTJSON_PAIR);
//
//        // Map<String, RedisCacheConfiguration> caches = new HashMap<>();
//        // // 缓存配置
//        // RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
//        //         .entryTtl(Duration.ofSeconds(60))
//        //         .disableCachingNullValues()
//        //         // .prefixKeysWith("redis.service")
//        //         .serializeKeysWith(stringPair)
//        //         .serializeValuesWith(fastJsonPair);
//        // caches.put("redis.service", config);
//        // return new TedisCacheManager(cacheWriter, defaultCacheConfig, caches);
//
//        return new SpringRedisCacheManager(cacheWriter, defaultCacheConfig);
//    }
//    @Bean
//    public CacheManager cacheManager(RedisConnectionFactory factory) {
//        //对象的序列化
//        RedisSerializationContext.SerializationPair valueSerializationPair
//                = RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer());
//        //全局redis缓存过期时间
//        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
//                .entryTtl(Duration.ofDays(1))
////                .serializeKeysWith()
//                .serializeValuesWith(valueSerializationPair);
//
//        return new RedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(factory), redisCacheConfiguration);
//    }

    private Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer() {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper());
        return jackson2JsonRedisSerializer;
    }

    private ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        return objectMapper;
    }
    @Override
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(method.getReturnType().getSimpleName());
                for (Object obj : params) {
                    sb.append(":");
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

    /**
     * 根据model的id生成缓存的key值
     * @return
     */
    @Bean
    public KeyGenerator keyGeneratorModelId() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(method.getReturnType().getSimpleName());

                for (Object object : params) {
                    sb.append("_");
                    BasePo model = (BasePo)object;
                    sb.append(model.getId());
                }

                return sb.toString();
            }
        };
    }


    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}
